package com.csg.ses.common.configuration;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csg.ses.common.utils.SnowFlakeUtil;
import com.csg.ses.dao.ses.YxzjkZwCsxxDao;
import com.csg.ses.dao.yxxt.YxxtYxzjkZwCsxxDao;
import com.csg.ses.entity.ses.YxzjkZwCsxxEntity;
import com.csg.ses.entity.yxxt.YxxtYxzjkZwCsxxEntity;
import com.csg.ses.feign.VcsService;
import com.csg.ses.feign.YxxtService;
import com.csg.ses.feign.ZncfFeign;
import com.csg.ses.service.ses.SysInterfaceLogService;
import com.csg.ses.vo.yxxt.YxxtInParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * @auther wangjun
 * @time 2020/11/20 15:17
 * 多线程定时任务
 */
@Component
@EnableScheduling
@EnableAsync
@EnableConfigurationProperties(SesConfig.class)
public class MultiThreadScheduleTask {

    @Autowired
    private VcsService vcsService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private SesConfig sesConfig;

    @Autowired
    private YxzjkZwCsxxDao sesCsxxDao;

    @Autowired
    private YxxtYxzjkZwCsxxDao yxxtCsxxDao;

    @Autowired
    private SysInterfaceLogService logService;

    @Autowired
    private ZncfFeign zncfFeign;

    @Autowired
    private YxxtService yxxtService;

    /**
     * 更新智能催费结果并通知营销系统
     * 指定服务器的ip和端口，且定时任务开关开启的情况下才执行定时任务内容
     */
    @Async
    @Scheduled(fixedDelayString = "${ses.timerPeriod}")
    public void gxcfjgTimer() {
        try {
            if ("true".equals(sesConfig.getTimerSwitch())) {
                String timerServer = serverConfig.getHostIp();
                if (sesConfig.getTimerServer().equals(timerServer)) {
                    String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Timestamp(System.currentTimeMillis()));
                    System.out.println(">>>>>>>服务器" + timerServer + "定时任务，更新智能催费结果并通知营销系统>>>>>>>" + currentTime + ">>>>>>>");
                    // 1.获取需要更新并通知营销系统的催费任务号和记录数（a.task_id is not null and a.znxtpch is null）
                    List<YxzjkZwCsxxEntity> taskList = sesCsxxDao.getTaskListAndJls();
                    for (YxzjkZwCsxxEntity task : taskList) {
                        String znxtpch = SnowFlakeUtil.nextStringId();
                        int num = 0;
                        String dqbm = "";
                        // 2.获取已完成催收的任务
                        JSONArray finishTask = vcsService.getTaskList(task.getTaskId(), null);
                        if (finishTask != null && finishTask.size() > 0) {
                            if ("finish".equals(finishTask.getJSONObject(0).getString("task_status"))) {
                                // 3.根据任务号获取任务详情
                                JSONArray taskDetails = vcsService.getPhoneRun(task.getTaskId(), null, task.getBz());

                                for (int i = 0; i < taskDetails.size(); i ++) {
                                    // 4.更新本地库催收结果信息
                                    JSONObject detail = taskDetails.getJSONObject(i);
                                    String sjhm = detail.getString("phone");
                                    String cfjg = detail.getString("call_status");
                                    String sbyy = detail.getString("hangup_cause");
                                    JSONObject variable = detail.getJSONObject("variable");
                                    String yhbh = variable.getString("用户编号");

                                    List<YxzjkZwCsxxEntity> sesCsxxList = sesCsxxDao.getCsxx(task.getTaskId(), sjhm, yhbh);
                                    for (YxzjkZwCsxxEntity sesCsxx : sesCsxxList) {
                                        sesCsxx.setZnxtpch(znxtpch);
                                        sesCsxx.setCfjg(cfjg);
                                        sesCsxx.setSbyy(sbyy);
                                        sesCsxxDao.updateById(sesCsxx);

                                        // 5.将催收信息更新到营销中间库
                                        YxxtYxzjkZwCsxxEntity yxxtCsxx = yxxtCsxxDao.selectById(sesCsxx.getTsbs());
                                        yxxtCsxx.setZnxtpch(znxtpch);
                                        yxxtCsxx.setCfjg("2".equals(cfjg) ? "0" : "1");
                                        yxxtCsxx.setSbyy(sbyy);
                                        yxxtCsxxDao.updateById(yxxtCsxx);
                                        dqbm = sesCsxx.getDqbm();
                                        num ++;
                                    }
                                }

                                // 6.调用营销接口发送电费催收结果（restful）
                                //this.fscfdhjgtz(dqbm, znxtpch, String.valueOf(num));

                                // 6.调用营销接口发送电费催收结果（webservice）
                                yxxtService.fscfdhjgtz(dqbm, znxtpch, String.valueOf(num), sesConfig.getWsUrl());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 调用营销接口发送电费催收结果（restful）
     * @param dqbm
     * @param znxtpch
     * @param pcjls
     */
    public Boolean fscfdhjgtz(String dqbm, String znxtpch, String pcjls) {
        YxxtInParam znpcxx = new YxxtInParam();
        znpcxx.setDqbm(dqbm);
        znpcxx.setZnxtpch(znxtpch);
        znpcxx.setPcjls(pcjls);

        Boolean isSuccess = false;
        String[] outParams = null;
        Long logId = logService.insertLog("发送催费电话结果通知", sesConfig.getRsUrl(), "yxxt", new String[] {JSON.toJSONString(znpcxx)});
        try {
            Map<String, String> result = zncfFeign.fscfdhjgtz(znpcxx);
            isSuccess = true;
            outParams = new String[] {JSON.toJSONString(result)};
        } catch (Exception e) {
            outParams = new String[] {"调用" + sesConfig.getRsUrl() + "接口失败！", e.getCause().getMessage()};
            e.printStackTrace();
        } finally {
            logService.updateLog(logId, isSuccess, outParams);
            return isSuccess;
        }
    }
}